#include <QGraphicsTextItem>
#include <QTextCursor>
#include <QPainter>

#include <UIKit/UIApplication.h>
#include <UIKit/UIKeyboard.h>
#include <UIKit/UIWindow.h>
#include <UIKit/UIDevice.h>
#include <UIKit/UIFont.h>
#include <UIKit/UIView.h>

#include "MainViewController.h"

class KeyboardTextDelegate : public UIKeyboardDelegate {
    public:
        KeyboardTextDelegate (QGraphicsTextItem *item) {
            m_textItem = item;
        }

        void keyPressed (const QChar& key) {
            m_textItem->textCursor().insertText(key);
        }

        void returnPressed (void) {
            m_textItem->textCursor().insertText("\n");
        }

        void backspacePressed (void) {
            m_textItem->textCursor().deletePreviousChar();
        }

    private:
        QGraphicsTextItem *m_textItem;
};


MainViewController::MainViewController (QObject *parent)
    : UIViewController(parent)
{
    UIDevice *device = UIDevice::currentDevice();
    device->beginGeneratingDeviceOrientationNotifications();
}

MainViewController::~MainViewController() {
}

void MainViewController::viewDidLoad (void) {
    UIWindow *window = new UIWindow;
    UIApplication::sharedApplication()->setKeyWindow(window);

    m_textItem = new QGraphicsTextItem;
    m_textItem->setFont(UIFontNormal(m_textItem->font()));
    m_textItem->setDefaultTextColor(Qt::white);
    m_textItem->setPos(0.0f, 0.0f);
    window->addItem(m_textItem);

    m_keyboard = new UIKeyboard;
    m_keyboard->setDelegate(new KeyboardTextDelegate(m_textItem));
    window->addItem(m_keyboard);

    orientationChanged();
}

void MainViewController::viewDidUnload (void) {
    qDebug("UNLOAD VIEW");
    delete m_textItem;
    delete m_keyboard;
}

void MainViewController::orientationChanged (void) {
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation())) {
        m_keyboard->setOrientation(UIKeyboardOrientationHorizontal);
        m_keyboard->setPos(0.0f, 285.0f);
    } else {
        m_keyboard->setOrientation(UIKeyboardOrientationVertical);
        m_keyboard->setPos(0.0f, 345.0f);
    }
}

bool MainViewController::shouldAutorotate (UIInterfaceOrientation orientation) const {
    Q_UNUSED(orientation)
    return(true);
}


